<?php 
/****

	If you want the best of the world,
give the world your best anytime！
            				——不二
                							
****/

defined('ACCESS')||exit('Forbidden!');

//前台页面
class IndexAction extends Action {
	protected $cat;
	protected $art;

	public function __construct(){
		parent::__construct();
		$this->cat = new CategoryModel();
		$this->art = new ArticleModel();
	}

	//首页
	public function index(){
		//取出所有栏目
		$cats = $this->cat->select();
		$this->assign('cats',$cats);


		//取出所有文章 
		$cnt = isset($_GET['page'])?$_GET['page']:1;
		$where = '1 order by art_id desc limit '. (($cnt-1)*2) .',2';
		$arts = $this->art->select($where);

		//分页
		$pager = $this->art->getPages(2);
		$this->assign('pager',$pager);

		$num = count($pager);
		$this->assign('num',$num);
		$this->assign('cnt',$cnt);

		$this->assign('arts',$arts);

		$this->display('index.html');
	}

	//取出相应栏目下的文章列表
	public function catpage(){
		$id = $this->I('id');
		$cnt = isset($_GET['page'])?$_GET['page']:1;
		$res = $this->art->select('cat_id='.$id.' order by art_id desc limit '. (($cnt-1)*2) .',2');
		if(!$res){
			echo "<script>alert('走错地儿了，该栏目下木有文章啊啊啊~~');location=window.history.back(-1);</script>";
		}else{
		
			$this->assign('arts',$res);

			//取出所有栏目
			$cats = $this->cat->select();
			$this->assign('cats',$cats);


			//分页
			$pager = $this->art->getPages(2,"cat_id=$id");
			$this->assign('pager',$pager);

			//将页码赋值到模板用于判断格式样式
			$num = count($pager);
			$this->assign('num',$num);
			$this->assign('cnt',$cnt);


			$this->display('index.html');
		}
	}

	//文章页
	public function artpage(){
		$id = $this->I('id');
		$res = $this->art->find($id);
		$com = new CommentModel();
		if(!$res){
			echo "<script>alert('走错地儿了，木有该文章啊啊啊~~');location=window.history.back(-1);</script>";
		}else{
			if(empty($_POST)){
				//栏目
				$cats = $this->cat->select();
				$this->assign('cats',$cats);

				//取出所有评论
				$coms = $com->select("art_id=$id");
				$this->assign('coms',$coms);

				$this->assign('art',$res);
				$this->display('read.html');
			}else {
				//写入评论
				
				$_POST['nickname'] = isset($_POST['nickname'])?$_POST['nickname']:'匿名';
				$_POST['art_id'] = $id;

				if(!isset($_POST['content'])){
					echo "<script>alert('内容不能为空');location=window.history.back(-1);</script>";
					exit();
				}

				//合法性验证
				if (empty($_POST['captcha'])) {
					echo "<script>alert('验证码不能为空');location=window.history.back(-1);</script>";
					exit();
				}
				//有效性
				if(!Captcha::checkCaptcha($_POST['captcha'])){
					echo "<script>alert('验证码错误');location=window.history.back(-1);</script>";
					exit();
				}

				//写入数据库
				$com->insert($_POST);

				//article中num+1
				$res['num'] +=1;
				$this->art->update($res);

				$ref = $_SERVER['HTTP_REFERER'];
				header("Location:$ref");
			}
		}
	}
}

